package io.github.ali.commons.codec;

import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author ALi
 * @version 1.0
 * @date 2023-03-27 17:08
 * @description
 */
public class Unicode {
    public static String toUnicode(String source) throws RuntimeException {
        if (source == null || source.length() == 0) {
            return source;
        }
        try {
            StringBuffer out = new StringBuffer();
            byte[] bytes = source.getBytes(Charset.UNICODE.VALUE);
            //跳过\ufeff
            for (int i = 2; i < bytes.length - 1; i += 2) {
                out.append("\\u");
                String str = Integer.toHexString(bytes[i + 1] & 0xff);
                String str1 = Integer.toHexString(bytes[i] & 0xff);
                for (int j = str1.length(); j < 2; j++) {
                    out.append("0");
                }
                out.append(str1);
                out.append(str);
            }
            return out.toString();
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("String to Unicode error!", e);
        }
    }

    public static String toString(String unicode){
        if (unicode == null || unicode.length() == 0) {
            return unicode;
        }
        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        Matcher matcher = pattern.matcher(unicode);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            unicode = unicode.replace(matcher.group(1), ch + "");
        }
        return unicode;

    }
}
